import axios from 'axios'
import qs from 'qs'
import Router from '../router'
import { getCookie } from '@/utils/cookie'

let _axios = axios.create({
  // baseURL: '/api',
  withCredentials: true,
  timeout: 0,
  // headers: { 'Content-Type':'application/json' },
  // transformRequest: [function (data) {
  //   if (data && data.isUpload) return data.formData
  //   else return data ? JSON.stringify(data) : JSON.stringify({})
  // }],
  transformRequest: [function (data) {
    data = data || {}
    if (data && data.axiosType === 'upload') {
      delete data.axiosType
      return JSON.stringify(data)
    } else {
      if (data && data.content) data.content = encodeURIComponent(JSON.stringify(data.content))
      else data['content'] = encodeURIComponent(JSON.stringify({}))
      if (data && data.isUpload) {
        return data.formData
      } else if (data && data.isLogin) {
        delete data.isLogin
        return data ? JSON.stringify(data) : JSON.stringify({})
      } else {
        return qs.stringify(data)
      }
    }
    
  }],

  paramsSerializer: function (params) {
    return qs.stringify(params)
  }
})

// 请求拦截器
_axios.interceptors.request.use(config => {
  config.headers.Accept = 'application/json'
  if (config.url === '/material/DesignerUserProcess/toLogin' || config.url.indexOf('SaveFile/saveFile') > -1 || config.url.indexOf('SupplierStorageController/supplierCheckIsExist') > -1 || config.url.indexOf('createSupplierStoragePage') > -1) config.headers['Content-Type'] = 'application/json'
  else config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
_axios.interceptors.response.use(res => {
  if (res.data.ResultSet && (res.data.ResultSet.status === 20000 || res.data.ResultSet.status === 20004) && Router.currentRoute.name !== 'login') Router.replace({name: 'login'})
  if (res.data.code === 0 || (res.data.ResultSet && res.data.ResultSet.status == 0)) return res.data
  else return Promise.reject(res.data)
}, err => {
  let originalRequest = err.config
  if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
    Message({
      message: '请检查网络再重新连接！',
      type: 'error'
    })
    return Promise.reject('请检查网络再重新连接！')
  }
  return Promise.reject(err.data)
})

export default _axios
